package com.qingcheng.service.impl;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.*;
import com.qingcheng.dao.OrderItemMapper;
import com.qingcheng.dao.OrderLogMapper;
import com.qingcheng.dao.OrderMapper;
import com.qingcheng.dao.ReturnOrderMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.entity.Result;
import com.qingcheng.feign.ReturnOrderFegin;
import com.qingcheng.pojo.order.*;
import com.qingcheng.send.CancelOrderSender;
import com.qingcheng.service.*;
import com.qingcheng.util.IdWorker;
import com.qingcheng.vo.goods.LookOrderVo;
import com.qingcheng.vo.goods.OrderDetailsVo;
import com.qingcheng.vo.goods.OrderListVo;
import com.qingcheng.vo.goods.OrderVo;
import com.rabbitmq.client.Return;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.sql.Array;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired(required = false)
    private OrderMapper orderMapper;
    @Autowired(required = false)
    private OrderItemMapper orderItemMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired(required = false)
    private OrderLogMapper orderLogMapper;

    @Autowired
    private ReturnOrderMapper returnOrderMapper;

    @Autowired
    private OrderLogService orderLogService;

    @Autowired
    private PreferentialService preferentialService;

    /**
     * 返回全部记录
     * @return
     */
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }

    @Override
    public Order queryById(String orderId) {
        return orderMapper.selectByPrimaryKey(orderId);
    }

    /**
     * 分页查询
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Order> findPage(int page, int size) {
        PageHelper.startPage(page,size);
        Page<Order> orders = (Page<Order>) orderMapper.selectAll();
        return new PageResult<Order>(orders.getTotal(),orders.getResult());
    }

    /**
     * 条件查询
     * @param searchMap 查询条件
     * @return
     */
    public List<Order> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return orderMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Order> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(example);
        return new PageResult<Order>(orders.getTotal(),orders.getResult());
    }

    /**
     * 根据Id查询 订单和订单详情列表
     * @param id
     * @return
     */
    @Transactional
    public Orders findById(String id) {
        Orders orders = new Orders();
        Order order = orderMapper.selectByPrimaryKey(id);
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId",id);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
        orders.setOrder(order);
        orders.setOrderItem(orderItems);
        return orders;
    }

    @Override
    public PageResult<OrderVo> selectAllDetermineOrder(Map<String,Object> searchMap,int page, int size) {
        PageHelper.startPage(page,size);
        Page<OrderVo> orders = (Page<OrderVo>) orderMapper.selectAllDetermineOrder();
        return new PageResult<OrderVo>(orders.getTotal(),orders.getResult());
    }

    @Override
    public List<Map> selectCount() {
        List<Map> list = orderMapper.selectCountStatus();
        for (Map map : list) {
            String  order_status = (String) map.get("order_status");
            switch (order_status) {
                case "0": map.put("lable","待付款"); continue;
                case "1": map.put("lable","待发货"); continue;
                case "2": map.put("lable","已发货"); continue;
                case "3": map.put("lable","已完成"); continue;
                case "4": map.put("lable","已关闭"); continue;
            }
        }
        return list;
    }

    /**
     * 批量发货
     * @param orders
     */
    @Transactional
    public void batchSend(List<Order> orders) {
        Date date = new Date();
        for (Order order : orders) {
            //判断物流单号和物流公司是否为空
            if (order.getLogisticId()==null){
                //如果为空则抛出异常
                throw  new RuntimeException("请选择物流公司!!");
            }

            if (order.getShippingCode()==null){
                throw new RuntimeException("物流单号不能为空!!");
            }
        }

        for (Order order : orders) {
            //如果都不为空 则更新订单状态、发货状态、发货时间,添加物流公司和物流单号
            order.setConsignTime(date);//发货时间
            order.setConsignStatus("1");//发货状态
            order.setOrderStatus("2");//订单状态
            orderMapper.updateByPrimaryKey(order);

            //记录订单日志
            OrderLog orderLog = new OrderLog();
            orderLog.setId(String.valueOf(idWorker.nextId()));      //分布式id
            orderLog.setOperater("daijinhua");  //操作员
            orderLog.setOperateTime(date);      //操作时间
            orderLog.setOrderId(order.getId()); //订单号
            orderLog.setOrderStatus("2");       //订单状态
            orderLog.setPayStatus("1");     //付款状态
            orderLog.setConsignStatus("2");    //发货状态
            orderLog.setRemarks("该订单已完成");    //备注

            orderLogMapper.insert(orderLog);
        }
    }

    @Override
    public List<Order> findByOids(Map<String,Object> searchMap) {
        List<Order> orderItems = new ArrayList<>();
        try {
            List<String> list = (List<String>) searchMap.get("ordersId");
            for (String s : list) {
                Example example  = new Example(Order.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("id",s);
                List<Order> orderItems1 = orderMapper.selectByExample(example);
                for (Order order : orderItems1) {
                    orderItems.add(order);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return orderItems;
    }

    @Override
    @Transactional
    public void mergeOrders(String orderId1, String orderId2) {
        // 生成订单id
        long orderId = idWorker.nextId();
        Date date = new Date();

        //查出订单和订单明细
        Order order1 = orderMapper.selectByPrimaryKey(orderId1);
        Order order2 = orderMapper.selectByPrimaryKey(orderId2);

        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId",order1.getId());
        List<OrderItem> orderItems1 = orderItemMapper.selectByExample(example);

        Example example2 = new Example(OrderItem.class);
        Example.Criteria criteria2 = example2.createCriteria();
        criteria2.andEqualTo("orderId",order2.getId());
        List<OrderItem> orderItems2 = orderItemMapper.selectByExample(example2);

        //创建新的订单
        Order o = new Order();
        BeanUtils.copyProperties(order1,o);
        o.setId(String.valueOf(orderId));
        if(order1.getTotalNum() == null && order2.getTotalNum()==null){
            throw  new RuntimeException("数量不能为空");
        }
        o.setTotalNum(order1.getTotalNum()+order2.getTotalNum());
        o.setTotalMoney(order1.getTotalMoney()+order2.getTotalMoney());
        o.setPreMoney(order1.getPreMoney()+order2.getPreMoney());
        o.setUpdateTime(date);
        int insert = orderMapper.insertSelective(o);
        if(insert<1){
            throw new RuntimeException("创建新订单失败");
        }

        //修改订单1的详情
        for (OrderItem orderItem : orderItems1) {
            orderItem.setOrderId(o.getId());
            orderItemMapper.updateByPrimaryKeySelective(orderItem);
        }

        //修改订单2的详情
//        for (OrderItem orderItem : orderItems2) {
//            orderItem.setOrderId(o.getId());
//            orderItemMapper.updateByPrimaryKeySelective(orderItem);
//        }

        order1.setIsDelete("1");
        orderMapper.updateByPrimaryKey(order1);
        order2.setIsDelete("1");
        orderMapper.updateByPrimaryKey(order2);

        //记录订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setId(idWorker.nextId()+"");  //分布式id
        orderLog.setOperater("heizai");  //操作员
        orderLog.setOperateTime(date);      //操作时间
        orderLog.setOrderId(o.getId()); //订单号
        orderLog.setOrderStatus("2");       //订单状态
        orderLog.setPayStatus("1");     //付款状态
        orderLog.setConsignStatus("2");    //发货状态
        orderLog.setRemarks("该订单已合并");    //备注

        orderLogMapper.insert(orderLog);
    }

    @Override
    @Transactional
    public void splitOrders(List<Map> maps) {
        Date date = new Date();
        long id = idWorker.nextId();

        //创建新的订单
        Order newOrder = new Order();
        newOrder.setId(id+"");

        for (Map map : maps) {
            String id1 = (String) map.get("id");
            Integer num1 = (Integer) map.get("num"); //拆分的数量
            OrderItem orderItem = orderItemMapper.selectByPrimaryKey(id1);
            Order order = orderMapper.selectByPrimaryKey(orderItem.getOrderId());
            BeanUtils.copyProperties(order,newOrder);
            newOrder.setId(id+"");

            Integer num2 = orderItem.getNum(); //数量
            if(num1>num2){
                throw new RuntimeException("拆分数量不能大于明细数量");
            }

            //修改之前的订单
            orderItem.setNum(num2-num1); //订单数
            orderItem.setMoney(orderItem.getPrice()*num2); //总个数
            orderItem.setPayMoney(orderItem.getPayMoney()+orderItem.getPostFee()); //支付金额
            orderItemMapper.updateByPrimaryKeySelective(orderItem);

            //生成新的订单
            OrderItem orderItem1 = new OrderItem();
            BeanUtils.copyProperties(orderItem,orderItem1);
            orderItem1.setOrderId(newOrder.getId());
            orderItem1.setId(idWorker.nextId()+"");
            orderItem1.setNum(num1); //订单数
            orderItem1.setMoney(orderItem.getPrice()*num1); //总个数
            orderItem1.setPayMoney(orderItem.getPayMoney()+orderItem.getPostFee()); //支付金额
            orderItemMapper.insertSelective(orderItem1);


            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId()+"");      //分布式id
            orderLog.setOperater("黑仔");  //操作员
            orderLog.setOperateTime(date);      //操作时间
            orderLog.setOrderId(order.getId()); //订单号
            orderLog.setOrderStatus(order.getOrderStatus());       //订单状态
            orderLog.setPayStatus(order.getPayStatus());     //付款状态
            orderLog.setConsignStatus(order.getConsignStatus());    //发货状态
            orderLog.setRemarks("以拆分成新的订单");    //备注
            orderLogMapper.insert(orderLog);
        }
        orderMapper.insert(newOrder);

    }

    @Override
    public LookOrderVo findOrderDetails(String id) {
        if(StringUtils.isEmpty(id)){
            throw  new RuntimeException("传入id为空");
        }
        //页面需要的数据
        LookOrderVo lookOrderVo = new LookOrderVo();

        // 查询订单信息
        OrderDetailsVo orderDetailsVo = orderMapper.selectOrderById(id);

        if(orderDetailsVo == null){
            throw new RuntimeException("订单不存在");
        }
        List list = new ArrayList();
        list.add(orderDetailsVo);

        // 查询商品信息
        List<Map> orderItemByOrderId = orderItemMapper.findLookOrderItem(orderDetailsVo.getId());
        for (Map map : orderItemByOrderId) { //封装页面数据
            String oldName = (String) map.get("name");
            String name = oldName.substring(0, oldName.indexOf(" "));
            String bName = "\n品牌:"+(String) map.get("bname");
            map.put("name",name+bName);
            Integer price = (Integer) map.get("price");
            String sn = (String) map.get("sn");
            map.put("snPrice","价格:"+price+"货号:"+sn);
            String s = (String) map.get("spec");
            Map parse = (Map) JSON.parse(s);
            StringBuffer spce = new StringBuffer();
            if(parse == null){
                return null;
            }
            for(Object s1:parse.keySet()){
                spce.append(s1+":"+parse.get(s1)+"\n");
            }
            map.put("attribute", spce);
            map.put("money",(Integer)map.get("num")*price);
        }
        OrderConfig orderConfig = orderConfigService.findById(1);
        orderDetailsVo.setTakeTimeout(orderConfig.getTakeTimeout());
        lookOrderVo.setOrderItems(orderItemByOrderId);

        // 查询操作信息
        List<OrderLog> orderLogByOrderId = orderLogService.findOrderLogByOrderId(orderDetailsVo.getId());
        lookOrderVo.setOrderLogs(orderLogByOrderId);

        //地址信息
        Map<String,Object> address = new ConcurrentHashMap<>();
        address.put("receiverContact",orderDetailsVo.getReceiver_contact());
        address.put("receiverMobile",orderDetailsVo.getReceiver_mobile());
        address.put("receiverAddress",orderDetailsVo.getReceiver_address());
        address.put("receiverCode",orderDetailsVo.getReceiver_code());
        List<Map> list1 = new ArrayList<Map>();
        list1.add(address);
        lookOrderVo.setAddressDetails(list1);

        //费用信息
        List<Map> costInformation = new ArrayList<>();
        Map map = new HashMap();

        Integer payMoney = 0; //商品合计
        Integer postFee = 0; //运费
        Integer specialOffer = 0; //活动优惠
        Integer orderSumMoney = 0;//订单总金额

        for (Map map1 : orderItemByOrderId) {
            Integer integer = (Integer) map1.get("money");
            Integer integer2 = (Integer) map1.get("post_fee");
            payMoney+=integer;
            postFee+=integer2;
        }
        orderSumMoney = payMoney-orderDetailsVo.getPre_money()+postFee;
        //活动优惠
        List<Preferential> preferentialByDay = preferentialService.findPreferentialByDay();
        for (Preferential preferential : preferentialByDay) {
            //计算订单的活动优惠
            if (preferential.getBuyMoney() <= orderSumMoney) {
                specialOffer = preferential.getPreMoney();
                orderDetailsVo.setPreferentialInfo(String.format("满%s减%s",preferential.getBuyMoney(),preferential.getPreMoney()));
                continue;
            }
        }

        map.put("total",payMoney); //商品合计
        map.put("postFee",postFee); //邮费
        map.put("preMoney",orderDetailsVo.getPre_money()); //优惠券
        map.put("specialOffer",specialOffer); //活动优惠
        map.put("orderSumMoney",orderSumMoney); //订单总金额
        map.put("amountDue",orderSumMoney-specialOffer); //应付款金额
        List list2  = new ArrayList();
        list2.add(map);
        lookOrderVo.setCostInformation(list2);
        List list3 = new ArrayList();
        list3.add(orderDetailsVo);
        lookOrderVo.setOrder(list3);
        return lookOrderVo;
    }

    @Override
    public void determineOrder(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new RuntimeException("id不能为空");
        }

        Order order = new Order();
        order.setId(id);
        order.setSourceType("4");

        orderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public void determineOrde2(List<String> ids) {
        if (ids.isEmpty()) {
            throw new RuntimeException("ids不能为空");
        }
        for (String id : ids) {
            Order order = new Order();
            order.setId(id);
            order.setSourceType("4");

            orderMapper.updateByPrimaryKeySelective(order);
        }

    }

    @Override
    public List<Map> returnOrderItemService(String orderId) {
        List<Map> orderItems = orderItemMapper.findOrderItemById(orderId);
        for (Map map : orderItems) {
            String oldName = (String) map.get("NAME");
            String name = oldName.substring(0, oldName.indexOf(" "));
            String bName = "\n品牌:"+(String) map.get("bname");
            map.put("name",name+bName);
            Integer price = (Integer) map.get("price");
            String sn = (String) map.get("sn");
            map.put("snPrice","价格:"+price+"货号:"+sn);
            String s = (String) map.get("spec");
            Map parse = (Map) JSON.parse(s);
            StringBuffer spce = new StringBuffer();
            if(parse == null){
                return null;
            }
            for(Object s1:parse.keySet()){
                spce.append(s1+":"+parse.get(s1)+"\n");
            }
            map.put("attribute", spce);
        }


        return orderItems;
    }

    /**
     * 根据订单状态查询数量
     * @param
     * @return
     */
    @Override
    public OrderInfoSum findByStatus(OrderInfoSum orderInfoSum) {
        orderInfoSum.setDfk_order_sum(orderMapper.findByStatus(0));
        orderInfoSum.setDfh_order_sum(orderMapper.findByStatus(1));
        orderInfoSum.setYfh_order_sum(orderMapper.findByStatus(2));
        orderInfoSum.setYwc_order_sum(orderMapper.findByStatus(3));
        orderInfoSum.setDclth_order_sum(returnOrderMapper.findByStatus("1"));
        orderInfoSum.setDcltksq_sum(returnOrderMapper.findByStatus("2"));
        return orderInfoSum;
    }

    @Override
    public void updatePayStatus(String orderId, String transactionId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if(order != null && "0".equals(order.getPayStatus())){
            //修改订单状态
            order.setOrderStatus("1"); // 订单状态
            order.setPayStatus("1"); // 支付状态
            order.setUpdateTime(new Date()); //修改日期
            order.setPayTime(new Date()); //支付时间
            order.setTransactionId(transactionId); //交易流水号
            orderMapper.updateByPrimaryKeySelective(order);//修改

            //记录订单日志
            OrderLog orderLog=new OrderLog();
            orderLog.setId(UUID.randomUUID().toString().substring(0,8));
            orderLog.setOperater("system");// 系统
            orderLog.setOperateTime(new Date());//当前日期
            orderLog.setOrderStatus("1");
            orderLog.setPayStatus("1");
            orderLog.setRemarks("支付流水号"+transactionId);
            orderLog.setOrderId(order.getId());
            orderLog.setConsignStatus("0");
            orderLogMapper.insert(orderLog);
        }
    }

    //查询单个用户的订单
    @Override
    public List<Order> selectOrderList(String username) {
        Example example=new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",username);
        return orderMapper.selectByExample(example);
    }

    @Autowired
    private WeixinPayService weixinPayService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private SkuFegin skuFegin;

    //关闭订单
    @Override
    public boolean closeOrder(String orderId,String transaction_id) {
        //关闭订单表
        Map<String, String> map = weixinPayService.closeOrderByOrderId(orderId);
        if("SUCCESS".equals(map.get("return_code\t"))){
            log.info("订单插入成功");
            updatePayStatus(orderId, transaction_id);

            List<OrderItem> orderItems = orderItemService.queryByOrderId(orderId);
            return skuFegin.deductionStock(orderItems);
        }else{
            log.info("订单关闭失败");
            return false;
        }
    }


    @Override
    public PageResult<OrderListVo> findOrderList(int page, int size, String username,String orderStatus) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",username);
        if(orderStatus != null){
            criteria.andEqualTo("orderStatus",orderStatus);
        }
        PageHelper.startPage(page,size);
        Page<Order> orderList = (Page<Order>)orderMapper.selectByExample(example);

        List<OrderListVo> orderListVos = new ArrayList<>();
        for (Order order : orderList) {
            OrderListVo orderListVo = new OrderListVo();
            List<OrderItem> orderItems = orderItemService.queryByOrderId(order.getId());
            orderListVo.setOrderItems(orderItems);
            BeanUtils.copyProperties(order,orderListVo);
            orderListVos.add(orderListVo);
        }
        return new PageResult<OrderListVo>(orderList.getTotal(),orderListVos);
    }

    @Autowired
    private ReturnOrderFegin returnOrderFegin;

    @Override
    public void updateAddress(Map map) {
        Order order = orderMapper.selectByPrimaryKey((String) map.get("id"));
        order.setReceiverAddress((String) map.get("receiverAddress"));
        order.setReceiverContact((String) map.get("receiverContact"));
        order.setReceiverMobile((String) map.get("receiverMobile"));
        order.setReceiverCode((String) map.get("receiverCode"));
        orderMapper.updateByPrimaryKeySelective(order);
        String username = order.getUsername();
        map.put("username",username);
        returnOrderFegin.selectByUserName(username);
        returnOrderFegin.updateAddressByUsername(map);
    }

    @Override
    public void closeOrder(Order order,String message) {
        //记录订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setId(String.valueOf(idWorker.nextId()));  //分布式id
        orderLog.setOperater(order.getUsername());  //操作员
        orderLog.setOperateTime(new Date());      //操作时间
        orderLog.setOrderId(order.getId()); //订单号
        orderLog.setOrderStatus("4");       //订单状态
        orderLog.setConsignStatus(order.getConsignStatus());
        orderLog.setPayStatus(order.getPayStatus());
        orderLog.setRemarks(message);    //备注

        orderLogMapper.insertSelective(orderLog);

        order.setOrderStatus("4"); //修改订单状态
        orderMapper.updateByPrimaryKeySelective(order);

    }

    @Override
    public PageResult<Order> determineOrderList(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderStatus",2);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(example);
        return new PageResult<Order>(orders.getTotal(),orders.getResult());
    }

    @Override
    public PageResult<Order> orderMessage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("consignStatus",2);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(example);
        return new PageResult<Order>(orders.getTotal(),orders.getResult());
    }

    @Override
    public Map<String, Array> getsum() {
        Map map = new LinkedHashMap();
        String[] list1 = new String[7];
        int[] list2 = new int[7];
        String[] list3 = new String[7];
        for (int i=6;i>=0;i--){
            String s = String.valueOf(LocalDate.now().minusDays(6-i));
            list1[i]=s;
            list2[i]=orderMapper.getSum(s);
            String s1 = orderMapper.getpaysum(s);
            if (s1==null){
                list3[i]="0";
            }else {
                list3[i]=s1;
            }
        }
        map.put("time",list1);
        map.put("sum",list2);
        map.put("paysum",list3);
        return map;
    }

    @Override
    public void changeOrderStatus(String orderId, String status) {
        Order order = new Order();
        order.setId(orderId);
        order.setOrderStatus(status);
        orderMapper.updateByPrimaryKeySelective(order);
    }

    @Autowired(required = false)
    private ReturnOrderMapper returnOrderMapper;

    @Autowired(required = true)
    private ReturnOrderItemMapper returnOrderItemMapper;

    @Override
    public void returnOrder2(String orderId,String type) {
        //创建订单
        Order order = orderMapper.selectByPrimaryKey(orderId);

        //创建订单详情并设置数据
        ReturnOrder returnOrder = new ReturnOrder();
        BeanUtils.copyProperties(order,returnOrder); //
        returnOrder.setId(idWorker.nextId()); //分布式id
        returnOrder.setOrderId(Long.valueOf(order.getId()));
        returnOrder.setApplyTime(new Date());
        returnOrder.setUserAccount(order.getUsername());
        returnOrderMapper.insertSelective(returnOrder);

        //根据订单查询订单详情
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId",order.getId());
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);

        //创建退货详情
        for (OrderItem orderItem : orderItems) {
            ReturnOrderItem returnOrderItem = new ReturnOrderItem();
            BeanUtils.copyProperties(orderItem,returnOrder);
            returnOrderItem.setId(idWorker.nextId());
            returnOrderItem.setCategoryId(Long.valueOf(orderItem.getCategoryId3()));
            returnOrderItemMapper.insert(returnOrderItem);
        }

    }

    @Autowired
    private CartService cartService;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private OrderConfigService orderConfigService;

    @Autowired
    private CancelOrderSender cancelOrderSender;

    /**
     * 新增
     * @param order
     */
    @Transactional
    public Map<String,Object> add(Order order) {
        Date date = new Date();
        //查询选中的购物车
        List<Map<String, Object>> newOrderItemList = cartService.findNewOrderItemList(order.getUsername());
        List<OrderItem> orderItems = newOrderItemList.stream()
                .filter(cart -> (boolean) cart.get("checked"))
                .map(cart -> (OrderItem) cart.get("item"))
                .collect(Collectors.toList());

        //扣减库存
        boolean b = skuFegin.deductionStock(orderItems);
        if(!b){
            throw new RuntimeException("扣减库存失败");
        }

        //保存订单主表
        try {
            order.setId(idWorker.nextId()+"");
            IntStream numStream = orderItems.stream().mapToInt(OrderItem::getNum);
            IntStream moneyStream = orderItems.stream().mapToInt(OrderItem::getMoney);

            int totalNum = numStream.sum();
            int totalMoney = moneyStream.sum();
            int preMoney = cartService.preferential(order.getUsername()); //满减优惠金额

            order.setTotalMoney(totalNum); //总数量
            order.setTotalMoney(totalMoney); //总金额
            order.setPreMoney(preMoney); //优惠金额
            order.setPayMoney(totalMoney-preMoney);//支付金额
            order.setCreateTime(date); //订单的创建时间
            order.setOrderStatus("0"); //订单状态
            order.setPayStatus("0"); ///支付状态
            order.setConsignStatus("0");//发货状态
            order.setIsDelete("1");
            order.setLogisticId(1);
            order.setActivityId(1);
            order.setOrderConfigId(1);
            order.setSourceType("5");
            order.setReceiverCode("100010");
            order.setPostFee(10);
            orderMapper.insert(order);

            //保存订单明细
            //打折比例
            double proportion = (double)order.getPayMoney()/totalMoney;

            for (OrderItem orderItem : orderItems) {
                orderItem.setId(idWorker.nextId()+"");
                orderItem.setOrderId(order.getId());
                orderItem.setPayMoney((int)(orderItem.getMoney()*proportion));
                orderItemMapper.insert(orderItem);
            }

            //查询订单延迟时间
            OrderConfig orderConfig = orderConfigService.findById(1);

            cancelOrderSender.sendMessage(Long.valueOf(order.getId()),orderConfig.getOrderTimeout());

        } catch (Exception e) {
            e.printStackTrace();
            amqpTemplate.convertAndSend("","queue.skuback",JSON.toJSONString(orderItems));
            throw new RuntimeException("订单生成失败"); //抛出异常，让其回滚！
        }

        //清除购物车
        cartService.deleteCart(order.getUsername());

        Map<String,Object> map = new HashMap<>();
        map.put("ordersn",order.getId());
        map.put("money",order.getPayMoney());

        return map;
    }

    /**
     * 修改
     * @param order
     */
    public void update(Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     *  删除
     * @param id
     */
    public void delete(String id) {
        orderMapper.deleteByPrimaryKey(id);
    }

    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 订单id
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andLike("id","%"+searchMap.get("id")+"%");
            }
            // 支付类型，1、在线支付、0 货到付款
            if(searchMap.get("payType")!=null && !"".equals(searchMap.get("payType"))){
                criteria.andLike("payType","%"+searchMap.get("payType")+"%");
            }
            // 物流名称
            if(searchMap.get("shippingName")!=null && !"".equals(searchMap.get("shippingName"))){
                criteria.andLike("shippingName","%"+searchMap.get("shippingName")+"%");
            }
            // 物流单号
            if(searchMap.get("shippingCode")!=null && !"".equals(searchMap.get("shippingCode"))){
                criteria.andLike("shippingCode","%"+searchMap.get("shippingCode")+"%");
            }
            // 用户名称
            if(searchMap.get("username")!=null && !"".equals(searchMap.get("username"))){
                criteria.andLike("username","%"+searchMap.get("username")+"%");
            }
            // 买家留言
            if(searchMap.get("buyerMessage")!=null && !"".equals(searchMap.get("buyerMessage"))){
                criteria.andLike("buyerMessage","%"+searchMap.get("buyerMessage")+"%");
            }
            // 是否评价
            if(searchMap.get("buyerRate")!=null && !"".equals(searchMap.get("buyerRate"))){
                criteria.andLike("buyerRate","%"+searchMap.get("buyerRate")+"%");
            }
            // 收货人
            if(searchMap.get("receiverContact")!=null && !"".equals(searchMap.get("receiverContact"))){
                criteria.andLike("receiverContact","%"+searchMap.get("receiverContact")+"%");
            }
            // 收货人手机
            if(searchMap.get("receiverMobile")!=null && !"".equals(searchMap.get("receiverMobile"))){
                criteria.andLike("receiverMobile","%"+searchMap.get("receiverMobile")+"%");
            }
            // 收货人地址
            if(searchMap.get("receiverAddress")!=null && !"".equals(searchMap.get("receiverAddress"))){
                criteria.andLike("receiverAddress","%"+searchMap.get("receiverAddress")+"%");
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if(searchMap.get("sourceType")!=null && !"".equals(searchMap.get("sourceType"))){
                criteria.andLike("sourceType","%"+searchMap.get("sourceType")+"%");
            }
            // 交易流水号
            if(searchMap.get("transactionId")!=null && !"".equals(searchMap.get("transactionId"))){
                criteria.andLike("transactionId","%"+searchMap.get("transactionId")+"%");
            }
            // 订单状态
            if(searchMap.get("orderStatus")!=null && !"".equals(searchMap.get("orderStatus"))){
                criteria.andLike("orderStatus","%"+searchMap.get("orderStatus")+"%");
            }
            // 支付状态
            if(searchMap.get("payStatus")!=null && !"".equals(searchMap.get("payStatus"))){
                criteria.andLike("payStatus","%"+searchMap.get("payStatus")+"%");
            }
            // 发货状态
            if(searchMap.get("consignStatus")!=null && !"".equals(searchMap.get("consignStatus"))){
                criteria.andLike("consignStatus","%"+searchMap.get("consignStatus")+"%");
            }
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andLike("isDelete","%"+searchMap.get("isDelete")+"%");
            }

            // 数量合计
            if(searchMap.get("totalNum")!=null ){
                criteria.andEqualTo("totalNum",searchMap.get("totalNum"));
            }
            // 金额合计
            if(searchMap.get("totalMoney")!=null ){
                criteria.andEqualTo("totalMoney",searchMap.get("totalMoney"));
            }
            // 优惠金额
            if(searchMap.get("preMoney")!=null ){
                criteria.andEqualTo("preMoney",searchMap.get("preMoney"));
            }
            // 邮费
            if(searchMap.get("postFee")!=null ){
                criteria.andEqualTo("postFee",searchMap.get("postFee"));
            }
            // 实付金额
            if(searchMap.get("payMoney")!=null ){
                criteria.andEqualTo("payMoney",searchMap.get("payMoney"));
            }

        }
        return example;
    }

    private Example createExample2(Map<String, Object> searchMap){
        Example example=new Example(OrderVo.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // name
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                criteria.andLike("name","%"+searchMap.get("name")+"%");
            }
            // 订单id
            if(searchMap.get("id")!=null ){
                criteria.andEqualTo("id",searchMap.get("id"));
            }
            // 支付类型，1、在线支付、0 货到付款
            if(searchMap.get("payType")!=null && !"".equals(searchMap.get("payType"))){
                criteria.andLike("payType","%"+searchMap.get("payType")+"%");
            }
            // 物流名称
            if(searchMap.get("shippingName")!=null && !"".equals(searchMap.get("shippingName"))){
                criteria.andLike("shippingName","%"+searchMap.get("shippingName")+"%");
            }
            // 物流单号
            if(searchMap.get("shippingCode")!=null && !"".equals(searchMap.get("shippingCode"))){
                criteria.andLike("shippingCode","%"+searchMap.get("shippingCode")+"%");
            }
            // 用户名称
            if(searchMap.get("username")!=null && !"".equals(searchMap.get("username"))){
                criteria.andLike("username","%"+searchMap.get("username")+"%");
            }
            // 买家留言
            if(searchMap.get("buyerMessage")!=null && !"".equals(searchMap.get("buyerMessage"))){
                criteria.andLike("buyerMessage","%"+searchMap.get("buyerMessage")+"%");
            }
            // 是否评价
            if(searchMap.get("buyerRate")!=null && !"".equals(searchMap.get("buyerRate"))){
                criteria.andLike("buyerRate","%"+searchMap.get("buyerRate")+"%");
            }
            // 收货人
            if(searchMap.get("receiverContact")!=null && !"".equals(searchMap.get("receiverContact"))){
                criteria.andLike("receiverContact","%"+searchMap.get("receiverContact")+"%");
            }
            // 收货人手机
            if(searchMap.get("receiverMobile")!=null && !"".equals(searchMap.get("receiverMobile"))){
                criteria.andLike("receiverMobile","%"+searchMap.get("receiverMobile")+"%");
            }
            // 收货人地址
            if(searchMap.get("receiverAddress")!=null && !"".equals(searchMap.get("receiverAddress"))){
                criteria.andLike("receiverAddress","%"+searchMap.get("receiverAddress")+"%");
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if(searchMap.get("sourceType")!=null && !"".equals(searchMap.get("sourceType"))){
                criteria.andLike("sourceType","%"+searchMap.get("sourceType")+"%");
            }
            // 交易流水号
            if(searchMap.get("transactionId")!=null && !"".equals(searchMap.get("transactionId"))){
                criteria.andLike("transactionId","%"+searchMap.get("transactionId")+"%");
            }
            // 订单状态
            if(searchMap.get("orderStatus")!=null && !"".equals(searchMap.get("orderStatus"))){
                criteria.andLike("orderStatus","%"+searchMap.get("orderStatus")+"%");
            }
            // 支付状态
            if(searchMap.get("payStatus")!=null && !"".equals(searchMap.get("payStatus"))){
                criteria.andLike("payStatus","%"+searchMap.get("payStatus")+"%");
            }
            // 发货状态
            if(searchMap.get("consignStatus")!=null && !"".equals(searchMap.get("consignStatus"))){
                criteria.andLike("consignStatus","%"+searchMap.get("consignStatus")+"%");
            }
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andLike("isDelete","%"+searchMap.get("isDelete")+"%");
            }

            // 数量合计
            if(searchMap.get("totalNum")!=null ){
                criteria.andEqualTo("totalNum",searchMap.get("totalNum"));
            }
            // 金额合计
            if(searchMap.get("totalMoney")!=null ){
                criteria.andEqualTo("totalMoney",searchMap.get("totalMoney"));
            }
            // 优惠金额
            if(searchMap.get("preMoney")!=null ){
                criteria.andEqualTo("preMoney",searchMap.get("preMoney"));
            }
            // 邮费
            if(searchMap.get("postFee")!=null ){
                criteria.andEqualTo("postFee",searchMap.get("postFee"));
            }
            // 实付金额
            if(searchMap.get("payMoney")!=null ){
                criteria.andEqualTo("payMoney",searchMap.get("payMoney"));
            }

        }
        return example;
    }


}
